package com.example.administrator.jinritoutiao.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2016/7/8.
 */
public class MyHttpUtil {

    private static MyHttpUtil myHttpUtil;
    private ByteArrayOutputStream os;
    private InputStream inputStream;

    private MyHttpUtil() {
    }

    public static MyHttpUtil getinstionce() {
        if (myHttpUtil == null) {
            myHttpUtil = new MyHttpUtil();
            return myHttpUtil;
        }

        return null;
    }

    public String mGetJson(String s) {
        try {
            URL url = new URL(s);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                os = new ByteArrayOutputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                return new String(os.toByteArray());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
